/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package me.aartikov.alligator;

import me.aartikov.alligator.helpers.RunInfoStackHelp;
import me.aartikov.alligator.util.Log;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilityLifecycleCallbacks;
import ohos.aafwk.content.IntentParams;

import ohos.utils.PacMap;

import java.util.Stack;


public class AbilityStack implements AbilityLifecycleCallbacks {
    /**
     * 普通
     */
    public final static int NORMOL = 0;
    /**
     * 返回至
     */
    public final static int BACKTO = 1;
    /**
     * 返回
     */
    public final static int BACK = 2;
    /**
     * 替换
     */
    public final static int REPLACE = 3;
    /**
     * 重置
     */
    public final static int RESET = 4;
    /**
     * 状态标签
     */
    public static final String STARTSTATE = "start_state";

    AbilityStack() {
    }

    private static volatile AbilityStack instance;

    /**
     * 单例获取
     * @return AbilityStack
     */
    public static AbilityStack getInstance() {
        AbilityStack lockInstance = instance;
        if (lockInstance == null) {
            synchronized (AbilityStack.class) {
                lockInstance = instance;
                if (lockInstance == null) {
                    lockInstance = instance = new AbilityStack();
                }
            }
        }
        return lockInstance;
    }

    Stack<Ability> abilities = new Stack<>();

    /**
     * 栈中是否存储了当前ability
     * @param ability 需要查询的的ability
     * @return int
     */
    public int isContainAbility(Ability ability) {
        return abilities.search(ability);
    }

    private void push(Ability ability) {
        Log.i("AbilityStack.push([ability]):40  添加:" + ability);
        abilities.push(ability);
    }

    private Ability pop() {
        Ability popAbility = null;
        if (!abilities.isEmpty()) {
            popAbility = abilities.pop();
        }
        Log.i("AbilityStack.pop([]):51   移除:" + popAbility);
        return popAbility;
    }

    /**
     * 获取当前栈顶的ability
     * @return Ability
     */
    public Ability peek() {
        if (!abilities.isEmpty()) {
            return abilities.peek();
        }
        return null;
    }

    private void goToAbilit(Ability ability) {
        Ability histroyAbility = pop();
        if (histroyAbility == null || histroyAbility.getClass().toString().equals(ability.getClass().toString())) {
            getInstance().push(ability);
            return;
        } else {
            histroyAbility.terminateAbility();
            goToAbilit(ability);
        }
    }


    /**
     * 替换栈顶的ability
     * @param ability 需要替换的ability
     */
    public void replace(Ability ability) {
        Ability histroyAbility = peek();
        if (histroyAbility != null) {
            try {
                histroyAbility.terminateAbility();
            } catch (Exception e) {
                Log.e("错误", "AbilityStack.replace([ability]):84");
                e.printStackTrace();
            }
        }
        getInstance().push(ability);
    }

    private void reset(Ability ability) {
        Ability histroyAbility = pop();
        if (histroyAbility != null) {
            try {
                histroyAbility.terminateAbility();
            } catch (IllegalStateException e) {
                Log.i("AbilityStack.reset([ability]):142  "+e.toString());
            }
            reset(ability);
        } else {
            getInstance().push(ability);
        }
    }

    private void doAction(Object param, Ability ability) {
        if (param instanceof Integer) {
            switch ((Integer) param) {
                case BACKTO:
                    getInstance().goToAbilit(ability);
                    break;
                case BACK:
                    getInstance().pop();
                    break;
                case REPLACE:
                    ability.setAbilitySliceAnimator(null);
                    ability.setTransitionAnimation(0, 0);
                    getInstance().replace(ability);
                    break;
                case RESET:
                    ability.setAbilitySliceAnimator(null);
                    ability.setTransitionAnimation(0, 0);
                    getInstance().reset(ability);
                    break;
                case NORMOL:
                default:
                    getInstance().push(ability);
                    break;
            }
        }
    }


    /**
     * ability生命周期中的start回调
     * @param ability 当前运行的ability
     */
    @Override
    public void onAbilityStart(Ability ability) {
        RunInfoStackHelp.getInstance().addAbility(ability);
        IntentParams intentParams = ability.getIntent().getParams();
        if (intentParams != null) {
            Object object = intentParams.getParam(AbilityStack.STARTSTATE);
            if (object != null) {
                doAction(intentParams.getParam(AbilityStack.STARTSTATE), ability);
            } else {
                doAction(AbilityStack.NORMOL, ability);
            }
        } else {
            doAction(AbilityStack.NORMOL, ability);
        }
    }

    /**
     * ability生命周期中的Active回调
     * @param ability 当前运行的ability
     */
    @Override
    public void onAbilityActive(Ability ability) {
    }

    /**
     * ability生命周期中的Inactive回调
     * @param ability 当前运行的ability
     */
    @Override
    public void onAbilityInactive(Ability ability) {
    }

    /**
     * ability生命周期中的Foreground回调
     * @param ability 当前运行的ability
     */
    @Override
    public void onAbilityForeground(Ability ability) {
    }

    /**
     * ability生命周期中的Background回调
     * @param ability 当前运行的ability
     */
    @Override
    public void onAbilityBackground(Ability ability) {
    }

    /**
     * ability生命周期中的Stop回调
     * @param ability 当前运行的ability
     */
    @Override
    public void onAbilityStop(Ability ability) {
        RunInfoStackHelp.getInstance().remove(ability);
        if (abilities.isEmpty()) {
            return;
        }
        if (getInstance().abilities.peek().toString().equals(ability.toString())) {
            getInstance().pop();
        }
    }

    /**
     * ability生命周期中的SaveState回调
     * @param pacMap 数据储存对象
     */
    @Override
    public void onAbilitySaveState(PacMap pacMap) {
    }
}
